<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace kitego\extend\login\admin\impl;

use app\dao\setting\SystemAdminDao;
use kitego\extend\login\admin\AdminLoginBase;
use kitego\utils\SnowflakeUtil;
use oauth\enum\OAuthEnum;
use oauth\OAuthProvider;

class AdminGiteeLoginImpl extends AdminLoginBase
{
    public function login($params)
    {
        $giteeUserInfo = $this->giteeUserInfo($params);

        $systemAdmin = $this->updateUser($giteeUserInfo['userInfo']);

        return $this->generateJwtToken($systemAdmin);
    }

    public function giteeUserInfo($params)
    {
        $oauthProvider = app()->make(OAuthProvider::class, [OAuthEnum::GITEE])->getStrategy();
        $accessToken = $oauthProvider->getAccessToken($params['code']);
        $userInfo = $oauthProvider->getUserInfo($accessToken);

        // 检测测试文件是否存在
        $testFilePath = app()->getRootPath() . '/extend/oauth/tests/gitee.php';
        if (file_exists($testFilePath)) {
            require_once $testFilePath;
            executeGiteeTest($oauthProvider, $accessToken);
        }

        return compact('accessToken', 'userInfo');
    }

    /**
     * 查找或创建用户
     */
    public function updateUser($userInfo)
    {
        $userData = [
            'account' => $userInfo['name'],
            'nickname' => $userInfo['name'],
            'avatar' => $userInfo['avatar_url'],
            'real_name' => $userInfo['name'],
            'delete_flag' => 0,
            'gitee_info' => json_encode($userInfo)
        ];

        $userId = app()->make(SystemAdminDao::class)->find([['gitee_id', '=', $userInfo['id']]])->id ?? null;

        if (!empty($userId)) {
            // 存在并更新数据
            $userData['update_time'] = now();

            $data = app()->make(SystemAdminDao::class)->update($userId, $userData, 'id');
            $data['id'] = $userId;
        } else {
            // 不存在则创建用户
            $userData['role_id'] = 3;
            $userData['gitee_id'] = $userInfo['id'];
            $userData['uuid'] = SnowflakeUtil::makeSnowflakeId();
            $userData['status'] = 1; // 管理员状态 1:有效 2:禁用 3:待审核
            $userData['create_time'] = now();

            $data = app()->make(SystemAdminDao::class)->save($userData);
        }

        return $data;
    }
}